package www.wen.com.common.lib.data.db.database

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import www.wen.com.common.lib.data.db.dao.*
import www.wen.com.common.lib.data.entities.builtIn.Cache
import www.wen.com.common.lib.util.ROOM_VERSION


/**
 * @author WEN
 * @Description:
 * @date 2020/11/2 16:07
 */
@Database(
        entities = [
            Cache::class,
        ], version = ROOM_VERSION
)
abstract class AppDatabase : RoomDatabase() {

    abstract fun getCacheDao(): CacheDao


    companion object {

        @Volatile
        private var instance: AppDatabase? = null
        private val LOCK = Any()

        operator fun invoke(context: Context) = instance ?: synchronized(LOCK) {
            instance ?: buildDatabase(context).also { instance = it }
        }

        fun getDB():AppDatabase{
            if(instance == null) throw Exception("数据库尚未初始化")
            return instance!!
        }

        private fun buildDatabase(context: Context) =
                Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "smart_print.db")
                        .fallbackToDestructiveMigration()
                        //允许主线程运行
                        .allowMainThreadQueries()
                        .build()
    }

}